import cv2
from numpy import *
import math

grayscale = 16


def F(x, y, img):
    return int(0.3*int(img[x, y, 0])+0.59*int(img[x, y, 1])+0.11*int(img[x, y, 2]))


def getP(filename, d_x, d_y):
    img = cv2.imread(filename)
    x = img.shape[0]
    y = img.shape[1]
    maxGray = 0
    for i in range(x):
        for j in range(y):
            if F(i, j, img) > maxGray:
                maxGray = F(i, j, img)
    P = zeros((grayscale+1, grayscale+1), int)
    if maxGray > grayscale:
        for i in range(1, x-1):
            for j in range(1, y-1):
                P[int(F(i, j, img)*grayscale / maxGray)
                  ][int(F(i+d_x, j+d_y, img)*grayscale / maxGray)] += 1
    else:
        for i in range(1, x-1):
            for j in range(1, y-1):
                P[F(i, j, img)][F(i+d_x, j+d_y, img)] += 1
    return P


def getMeanValue(x):
    return mean(x)


def getStandardDeviation(x):
    m = mean(x)
    sum = 0
    for i in range(len(x)):
        sum = (x[i]-m)**2
    return math.sqrt(sum/(len(x)-1))


def getFeatureVector(P):  # 对比度的纹理特征
    COM = 0
    ASM = 0
    REL = 0
    ENG = 0
    for i in range(P.shape[0]):
        for j in range(P.shape[1]):
            COM += (i-j)**2*P[i][j]
            ASM += P[i][j]*P[i][j]
            if getStandardDeviation(P[i])*getStandardDeviation(P[j]) != 0:
                REL += ((i-getMeanValue(P[i, :]))*(j-getMeanValue(P[:, j]))*P[i][j])/(
                    getStandardDeviation(P[i])*getStandardDeviation(P[j]))
            if P[i][j] > 0.0:
                ENG += P[i][j]*math.log(P[i][j])
    return COM, ASM, REL, ENG


def getFeature(filename):
    com = []
    asm = []
    rel = []
    eng = []
    P = getP(filename, 1, 0)
    COM, ASM, REL, ENG = getFeatureVector(P)
    com.append(COM)
    asm.append(ASM)
    rel.append(REL)
    eng.append(ENG)
    P = getP(filename, 0, 1)
    COM, ASM, REL, ENG = getFeatureVector(P)
    com.append(COM)
    asm.append(ASM)
    rel.append(REL)
    eng.append(ENG)
    P = getP(filename, 1, 1)
    COM, ASM, REL, ENG = getFeatureVector(P)
    com.append(COM)
    asm.append(ASM)
    rel.append(REL)
    eng.append(ENG)
    P = getP(filename, -1, 1)
    COM, ASM, REL, ENG = getFeatureVector(P)
    com.append(COM)
    asm.append(ASM)
    rel.append(REL)
    eng.append(ENG)

    return [getMeanValue(com), getMeanValue(asm), getMeanValue(rel), getMeanValue(eng), getStandardDeviation(com), getStandardDeviation(asm), getStandardDeviation(rel), getStandardDeviation(eng)]
